<template>
  <div class="admin-order-management">
    <!-- 订单类型切换 -->
    <el-radio-group v-model="orderType" style="margin-bottom: 20px;">
      <el-radio label="ordercqs">存取订单</el-radio>
      <el-radio label="ordpays">充值订单</el-radio>
    </el-radio-group>

    <!-- 存取订单表格 -->
    <el-table v-if="orderType === 'ordercqs' && ordercqsData" :data="ordercqsData" style="width: 100%;" stripe
      :header-cell-style="{ color: '#333' }">
      <el-table-column prop="id" label="ID" sortable />
      <el-table-column prop="orderNum" label="订单号" sortable />
      <el-table-column prop="cabinetNum" label="柜号" sortable />
      <el-table-column prop="cunId" label="存ID" sortable />
      <el-table-column prop="quId" label="取ID" sortable />
      <el-table-column prop="state" label="状态" sortable />
      <el-table-column prop="createdAt" label="使用时间" sortable>
        <template #default="scope">
          {{ formatDate(scope.row.createdAt) }}
        </template>
      </el-table-column>
      <el-table-column prop="updatedAt" label="取件时间" sortable>
        <template #default="scope">
          {{ formatDate(scope.row.updatedAt) }}
        </template>
      </el-table-column>
      <el-table-column prop="cabinetBelong" label="柜所属" sortable />
      <el-table-column prop="quCode" label="取件码" sortable />
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleEdit('ordercqs', scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDelete('ordercqs', scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 充值订单表格 -->
    <el-table v-if="orderType === 'ordpays' && ordpaysData" :data="ordpaysData" style="width: 100%;" stripe
      :header-cell-style="{ color: '#333' }">
      <el-table-column prop="id" label="ID" sortable />
      <el-table-column prop="orderNum" label="订单号" sortable />
      <el-table-column prop="user_id" label="用户ID" sortable />
      <el-table-column prop="type" label="类型" sortable />
      <el-table-column prop="des" label="描述" sortable />
      <el-table-column prop="amount" label="金额" sortable />
      <el-table-column prop="createdAt" label="创建时间" sortable>
        <template #default="scope">
          {{ formatDate(scope.row.createdAt) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleEdit('ordpays', scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDelete('ordpays', scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-state">
      <el-icon size="30px"><Loading /></el-icon> 加载中...
    </div>
    <div v-if="error" class="error-state">
      <el-icon size="20px"><Warning /></el-icon> {{ error }}
    </div>

    <!-- 编辑弹窗 -->
    <el-dialog v-model="editDialogVisible" :title="`编辑 ${orderType === 'ordercqs' ? '存取订单' : '充值订单'}`" width="30%">
      <el-form :model="editForm" :rules="editRules" ref="editFormRef" label-width="100px">
        <el-form-item v-if="orderType === 'ordercqs'" label="柜号" prop="cabinetNum">
          <el-input v-model="editForm.cabinetNum" />
        </el-form-item>
        <el-form-item v-if="orderType === 'ordercqs'" label="存ID" prop="cunId">
          <el-input v-model.number="editForm.cunId" />
        </el-form-item>
        <el-form-item v-if="orderType === 'ordercqs'" label="取ID" prop="quId">
          <el-input v-model.number="editForm.quId" />
        </el-form-item>
        <el-form-item v-if="orderType === 'ordercqs'" label="状态" prop="state">
          <el-select v-model="editForm.state" placeholder="请选择状态">
            <el-option label="已取" value="已取" />
            <el-option label="未取" value="未取" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="orderType === 'ordercqs'" label="柜所属" prop="cabinetBelong">
          <el-input v-model="editForm.cabinetBelong" />
        </el-form-item>
        <el-form-item v-if="orderType === 'ordercqs'" label="取件码" prop="quCode">
          <el-input v-model="editForm.quCode" />
        </el-form-item>
        <el-form-item v-if="orderType === 'ordpays'" label="用户ID" prop="user_id">
          <el-input v-model.number="editForm.user_id" />
        </el-form-item>
        <el-form-item v-if="orderType === 'ordpays'" label="类型" prop="type">
          <el-select v-model="editForm.type" placeholder="请选择类型">
            <el-option label="充值" value="充值" />
            <el-option label="提现" value="提现" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="orderType === 'ordpays'" label="描述" prop="des">
          <el-input v-model="editForm.des" />
        </el-form-item>
        <el-form-item v-if="orderType === 'ordpays'" label="金额" prop="amount">
          <el-input v-model.number="editForm.amount" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmEdit">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'
import { Loading, Warning } from '@element-plus/icons-vue'
import { showMsg } from '@/utils/showMsg'
import { layout } from '@/utils/layout'

export default {
  name: 'AdminOrderManagement',
  components: {
    Loading,
    Warning
  },
  data()
  {
    return {
      orderType: 'ordercqs', // 默认显示存取订单
      ordercqsData: null, // 存取订单数据
      ordpaysData: null, // 充值订单数据
      loading: false, // 加载状态
      error: null, // 错误信息
      editDialogVisible: false, // 编辑弹窗状态
      editForm: {}, // 编辑表单数据
      editRules: {
        cabinetNum: [{ required: true, message: '请输入柜号', trigger: 'blur' }],
        cunId: [{ required: true, message: '请输入存ID', trigger: 'blur' }],
        quId: [{ required: true, message: '请输入取ID', trigger: 'blur' }],
        state: [{ required: true, message: '请选择状态', trigger: 'change' }],
        cabinetBelong: [{ required: true, message: '请输入柜所属', trigger: 'blur' }],
        quCode: [{ required: true, message: '请输入取件码', trigger: 'blur' }],
        user_id: [{ required: true, message: '请输入用户ID', trigger: 'blur' }],
        type: [{ required: true, message: '请选择类型', trigger: 'change' }],
        des: [{ required: true, message: '请输入描述', trigger: 'blur' }],
        amount: [{ required: true, message: '请输入金额', trigger: 'blur' }]
      },
      editFormRef: null // 表单引用
    }
  },
  created()
  {
    this.fetchOrders()
    console.log('AdminOrderManagement component initialized')
  },
  methods: {
    // 获取订单数据
    async fetchOrders()
    {
      this.loading = true
      this.error = null
      try
      {
        const [ordercqsResponse, ordpaysResponse] = await Promise.all([
          axios.get('/node/ordercqs/getAll'),
          axios.get('/node/ordpays/getAll')
        ])
        if (ordercqsResponse.data.code === 0)
          this.ordercqsData = ordercqsResponse.data.data
        else
          layout(this, true, '登录凭证失效,清重新登录')
        if (ordpaysResponse.data.code === 0)
          this.ordpaysData = ordpaysResponse.data.data
        else
          layout(this, true, '登录凭证失效,清重新登录')
      }
      catch (error)
      {
        layout(this, error, '登录凭证失效,清重新登录')
      }
      finally
      {
        this.loading = false
      }
    },

    // 格式化日期为 YYYY-MM-DD HH:MM:SS
    formatDate(dateStr)
    {
      return new Date(dateStr).toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false
      }).replace(/\//g, '-').replace(/\b(\d)\b/g, '0$1')
    },

    // 处理编辑
    handleEdit(type, row)
    {
      this.orderType = type
      this.editForm = { ...row } // 深拷贝原始数据
      this.editDialogVisible = true
    },

    // 确认编辑
    confirmEdit()
    {
      this.$refs.editFormRef.validate(async(valid) =>
      {
        if (valid)
        {
          try
          {
            // 准备请求数据，移除 id 字段
            const { id, ...updateData } = this.editForm
            let response
            if (this.orderType === 'ordercqs')
              response = await axios.put(`/node/ordercqs/update/${this.editForm.id}`, updateData)
            else
              response = await axios.put(`/node/ordpays/update/${this.editForm.id}`, updateData)
            if (response.data.code === 0)
            {
              showMsg('修改成功', null, 'success')
              this.fetchOrders() // 刷新数据
              this.editDialogVisible = false
            }
            else
              showMsg('保存失败', null, 'warning')
          }
          catch (error)
          {
            layout(this, error, '登录凭证失效,清重新登录')
          }
        }
      })
    },

    // 处理删除
    async handleDelete(type, id)
    {
      this.$confirm('此操作将永久删除该订单, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() =>
      {
        try
        {
          let response
          if (type === 'ordercqs')
            response = await axios.delete(`/node/ordercqs/del/${id}`)
          else
            response = await axios.delete(`/node/ordpays/del/${id}`)
          if (response.data.code === 0)
          {
            showMsg('删除成功', null, 'success')
            this.fetchOrders() // 刷新数据
          }
          else
            showMsg('删除失败', null, 'warning')
        }
        catch (error)
        {
          layout(this, true, '登录凭证失效')
        }
      }).catch(() =>
      {
        showMsg('已取消删除', null, 'info')
      })
    }
  }
}
</script>

<style scoped>
.admin-order-management {
  user-select: none;
  padding: 20px;
  height: 90vh;
  background-color: #fff;
  color: #333;
  overflow: hidden;
}

.loading-state,
.error-state {
  text-align: center;
  padding: 20px;
  color: #666;
}

.error-state {
  color: #ff4444;
}

:deep(.el-table) {
  background-color: #fff;
  border-radius: 0;
  overflow: hidden;
}

:deep(.el-table__body tr:hover > td) {
  background-color: #f5f5f5 !important;
}

:deep(.el-table__row) {
  transition: all 0.3s ease;
}

:deep(.el-table__header th) {
  background-color: #f0f0f0; /* 浅灰色表头 */
}

:deep(.el-dialog) {
  border-radius: 10px;
}

:deep(.el-dialog__body) {
  padding: 20px;
}
</style>
